﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TCPHelper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            GetNativeIp();
            Port.Text = "8080";
        }
        bool status = false;//服务开启状态
        private string linebreak = "\r\n";
        Socket socketWatch = null;
        Thread threadWatch = null; 
        private void Openserver_Click(object sender, EventArgs e)
        {
            if (status == false)
            {
            //创立一个监听客户端消息的对象
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定用户输入的ip和地址
            socketWatch.Bind(new IPEndPoint(IPAddress.Parse(IpAddress.Text.Trim()), int.Parse(Port.Text.Trim()) ));
            socketWatch.Listen(30);//指定等待连接队列的最大长度
            //创建一个监听线程
            threadWatch = new Thread(ConnectWatch);
            threadWatch.IsBackground = true;
            threadWatch.Start();
            ChatList.AppendText("开始监听客户端消息---" + GetNowTime()+linebreak);
            status = true;
            Openserver.Text = "关闭服务";
            }
            else if(status == true)
            {
                Openserver.Text = "打开服务";
                ChatList.Text = string.Empty;
                ShutdownSocket();
                
            }
           
        }
        //关闭服务
        public void ShutdownSocket()
        {
            
             
            status = false;
            socketWatch.Close();
            socketWatch = null;
            socketConnection.Close();
            socketConnection = null;
 
        }
        Socket socketConnection = null;
        //接收数据
        private void ConnectWatch()
        {
            while (true)
            {

                    if (socketWatch == null) return;
                    socketConnection = socketWatch.Accept();//接受客户端请求，并返回一个和客户端进行通讯的socket对象
                    if (socketConnection == null) continue;
                    else {
                    if (Openserver.Text == "打开服务") return;
                    ChatList.Invoke(new Action(() => { ChatList.AppendText("客户端连接成功！" + GetNowTime() + linebreak); }));
                    try
                    {

                        while (true)
                        {
                            byte[] data = new byte[1024 * 2];
                            int length = socketConnection.Receive(data);//将收到的数据存入缓存区并返回收到的字节数
                            string recivedata = Encoding.UTF8.GetString(data).Replace("\0", "");
                            string str = "客户端：" + GetNowTime() + linebreak + recivedata + linebreak;
                            ChatList.Invoke(new Action(() => { ChatList.AppendText(str); }));
                        }
                    }
                    catch(Exception e)
                    {   
                        
                        ChatList.Invoke(new Action(() => { ChatList.AppendText(e.Message+linebreak); }));
                    }
                  
                }
                
            }
        }

        public void GetNativeIp()
        {    
             IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
             foreach(var ip in hostEntry.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    IpAddress.Text = ip.ToString();
                }
            }
        }
        public string GetNowTime()
        {
            string time = DateTime.Now.ToString();
            return  time;
        }
        public void SendMessage(string message)
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            socketConnection.Send(data);
            ChatList.AppendText("服务器发送: "  + GetNowTime() + linebreak+message+linebreak);
        }
        private void btn_send_Click(object sender, EventArgs e)
        {
            if (status == true)
            {
                if (SendData.Text.Length > 0)
                {
                    SendMessage(SendData.Text.Trim());
                }
                else MessageBox.Show("发送消息不能为空");
            }

            else MessageBox.Show("请先开启服务");
        }

    }
}
